package cn.piggy.gateway.core.datasource.connection;

import cn.piggy.gateway.core.common.CommonUtil;
import cn.piggy.gateway.core.http.HttpStatement;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URI;
import java.util.LinkedList;
import java.util.Map;


public class HttpConnection implements Connection {

    private final HttpPost httpPost;
    private final LinkedList<String> list;
    private final CloseableHttpClient client;
    public HttpConnection(LinkedList<String> list) {
        this.list = list;
        httpPost = new HttpPost();
        httpPost.addHeader("accept", "*/*");
        httpPost.addHeader("connection", "Keep-Alive");
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
        client = HttpClients.createDefault();
    }



    @Override
    public Object execute(HttpStatement httpStatement, Map<String, Object> params) {
        String res = null;
        try {
            String address = CommonUtil.getAddress(list);
            httpPost.setURI(URI.create(address+httpStatement.getUri()));
            String body = JSON.toJSONString(params);
            StringEntity entity = new StringEntity(body, "UTF-8");
//            entity.setContentEncoding("UTF-8");
//            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            CloseableHttpResponse response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = response.getEntity();
                res = EntityUtils.toString(httpEntity);
            }
        } catch (IOException e) {
            e.printStackTrace();
            res =" fail";
        }
        return res;
    }

}
